package com.panda.task;

import com.panda.entity.po.Article;
import com.panda.entity.po.Video;
import com.panda.mapper.ArticleMapper;
import com.panda.mapper.VideoMapper;
import com.panda.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class RefreshVisitCountTask {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private RedisCache redisCache;


    //访问量定时任务
    @Scheduled(cron = "0 0 1 * * ?")
    public void refreshViews() {
        List<Article> articles = articleMapper.selectList(null);
        articles.forEach(article -> {
            // 获取每一篇文章在redis中的浏览量，存入到数据库中
            String key = "views:article:" + article.getId();
            Long view = redisCache.size(key);
            if (view > 0) {
                Long views = view + article.getViews();
                article.setViews(views);
                int num = articleMapper.updateById(article);
                if (num != 0) {
                    redisCache.del(key);
                }
            }
        });
        List<Video> videos = videoMapper.selectList(null);
        videos.forEach(video -> {
            // 获取每一篇文章在redis中的浏览量，存入到数据库中
            String key = "views:video:" + video.getId();
            Long view = redisCache.size(key);
            if (view > 0) {
                Long views = view + video.getViews();
                video.setViews(views);
                int num = videoMapper.updateById(video);
                if (num != 0) {
                    redisCache.del(key);
                }
            }
        });
    }

    //历史记录定时任务
    @Scheduled(cron = "0 0 1 * * ?")
    public void refreshHistories() {

    }
}
